package cn.miao.direct;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.nio.charset.StandardCharsets;

/**
 * @program: QuickStart-RabbitMQ
 * @description: 生产者-direct模式 指定路由key进行发送
 * @author: MiaoWei
 * @create: 2021-10-19 18:28
 **/
public class Producer {

    public static void main(String[] args) {

        //1: 创建连接工程
        ConnectionFactory connectionFactory = new ConnectionFactory();
        //2: 设置连接属性
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("admin");
        connectionFactory.setVirtualHost("/");

        Connection connection = null;
        Channel channel = null;
        try {
            //3: 从连接工厂中获取连接
            connection = connectionFactory.newConnection("生产者");
            //4: 从连接中获取信道channel
            channel = connection.createChannel();
            //5: 准备消息发送的内容
            String message = "你好啊!direct路由模式!";
            String exchangeName = "direct-exchange";
            //指定路由key进行发送,由于我们使用direct类型的交换机和队列绑定,使用routing key,所以我们只需要给路由key,那么
            //对应的队列就会收到消息
            String routingKey1 = "order";
            String routingKey2 = "course";

            /**
             * 6: 发送消息给中间件rabbitmq-server
             * @Params1 :交换机exchange
             * @Params2 :队列名称/routingkey
             * @Params3 :属性配置
             * @Params4 :发送消息的内容
             */
            channel.basicPublish(exchangeName, routingKey1, null, message.getBytes(StandardCharsets.UTF_8));
            channel.basicPublish(exchangeName, routingKey2, null, message.getBytes(StandardCharsets.UTF_8));

            System.out.println("消息发送成功!");

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("发送消息出现异常...");
        } finally {
            //7.关闭通道
            if (channel != null && channel.isOpen()) {
                try {
                    channel.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            //8.关闭连接
            if (connection != null && connection.isOpen()) {
                try {
                    connection.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
